import os
import datetime
import numpy as np
from queue import Empty


class sEMG_Data_Recorder:
    """
    该类用于保存数据到txt文件中
    """

    def __init__(self, data_queue, stop_event):
        self.stop_event = stop_event
        self.data_queue = data_queue
        self.begin_time = None
        self.file_path = None
        self.file_handle = None

    def start_record(self):
        # 根据当前时间生成文件名
        file_name = "实验记录SEMG" + str(datetime.datetime.now().strftime('%Y%m%d%H%M%S')) + ".txt"
        file_dir = "./record_data"
        os.makedirs(file_dir, exist_ok=True)
        file_path = os.path.join(file_dir, file_name)
        self.file_path = file_path
        self.file_handle = open(file_path, 'w')
        self.file_handle.write("semg\t\n")  # 将数据写入文件，这里假设data可以直接转换为字符串写入，你可根据实际情况调整

    def stop_record(self):
        try:
            if self.file_handle and not self.file_handle.closed:
                self.file_handle.flush()
                os.fsync(self.file_handle.fileno())  # 强制写入磁盘
                self.file_handle.close()
        except Exception as e:
            print(f"Error closing file: {e}")
        finally:
            self.file_handle = None

    def update_data(self, timeout=1):

        try:
            while not self.stop_event.is_set():
                data = self.data_queue.get(timeout=timeout)
                # timestamp = int(
                #     (datetime.datetime.now() - self.begin_time).total_seconds() * 1000) if self.begin_time else 0
                np.savetxt(self.file_handle, data, fmt='%d', delimiter='\t')
                self.file_handle.flush()  # 确保数据立即写入文件
        except Empty:
            pass
        except Exception as e:
            print(f"Error writing data: {e}")


def sEMG_record_process(data_queue, stop_event):
    recorder = sEMG_Data_Recorder(data_queue, stop_event)
    try:
        recorder.start_record()
        recorder.update_data()
    except KeyboardInterrupt:
        print("Recording stopped by user.")
    except Exception as e:
        print(f"Unexpected error: {e}")
    finally:
        recorder.stop_record()
